<link rel="stylesheet" href="${request.contextPath}/static/oms/iframe/plugins/fileupload/css/jquery.fileupload-ui.css">
<link type="text/css" href="${request.contextPath}/static/oms/iframe/plugins/jeditor/css/jeditor.css" rel="stylesheet" />
<link href="${request.contextPath}/static/oms/iframe/plugins/bootstrap-image-picker/css/image-picker.css"  rel="stylesheet" type="text/css" />
<div class="row">
	<div class="col-md-12">
		<form id="editForm" class="form-horizontal" action="${request.contextPath}/cms/ad/update" method="post" onsubmit="return false">
			<input type="hidden" id="id" name="id" value="${cmsAd.id}">
			<div class="box-body">
				<div class="form-group">
					<label id="adCategoryIdLabel" for="adCategoryId" class="col-sm-2  control-label">广告类目</label>
					<div class="col-sm-10">
						<select class="form-control" id="adCategoryId"  name="adCategoryId" style="width: 100%;" placeholder="选择广告类目...">
						</select>
					</div>
				</div>
				<div class="form-group">
					<label id="adNameLabel" for="adName" class="col-sm-2 control-label">名称</label>
					<div class="col-sm-4">
						<input type="text" class="form-control" name="name" id="adName"  value="${cmsAd.name}" placeholder="输入名称...">
					</div>
					<label id="adCodeLabel" for="adCode" class="col-sm-2 control-label">编码</label>
					<div class="col-sm-4">
						<input type="text" class="form-control" name="code" id="adCode"  value="${cmsAd.code}" placeholder="输入编码...">
					</div>
				</div>
				<div class="form-group">
					<label id="adDescriptionLabel" class="col-sm-2 control-label" >描述</label>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="description" id="adDescription"  value="${cmsAd.description}" placeholder="输入描述...">
					</div>
				</div>
				<div class="form-group">
					<label id="adThumbnailLabel" for="adThumbnail" class="col-sm-2 control-label">缩略图</label>
					<div class="col-sm-7">
						<input type="text" class="form-control" name="thumbnail" id="adThumbnail"  value="${cmsAd.thumbnail}" placeholder="输入缩略图...">
					</div>
					<div class="col-sm-3">
						<span class="btn btn-success fileinput-button">
							<i class="glyphicon glyphicon-plus"></i>
							<span>选择文件</span>
							<input id="adThumbnailFileupload"  class="fileinput-button"  type="file" name="file"  data-url="/system/config/file/add?type=1" multiple>
						 </span>
					</div>
				</div>
				<div class="form-group">
					<label id="adBannerLabel" class="col-sm-2 control-label" >横幅图</label>
					<div class="col-sm-7">
						<input type="text" class="form-control" name="banner" id="adBanner"  value="${cmsAd.banner}" placeholder="输入横幅图...">
					</div>
					<div class="col-sm-3">
						<span class="btn btn-success fileinput-button">
							<i class="glyphicon glyphicon-plus"></i>
							<span>选择文件</span>
							<input id="adBannerFileupload"  class="fileinput-button"  type="file" name="file"  width="60" data-url="/system/config/file/add?type=1" multiple>
						 </span>
					</div>
				</div>
				<div class="form-group">
					<label id="adTargetLabel" for="adTarget" class="col-sm-2  control-label">打开方式</label>
					<div class="col-sm-4">
						<input type="text" class="form-control" name="target" value="${cmsAd.target}" id="adTarget"  placeholder="输入打开方式...">
					</div>
					<label id="adLinkUrlLabel" for="adLinkUrl" class="col-sm-2  control-label">链接地址</label>
					<div class="col-sm-4">
						<input type="text" class="form-control" name="linkUrl" value="${cmsAd.linkUrl}" id="adLinkUrl"  placeholder="输入链接地址...">
					</div>
				</div>
				<div class="form-group">
					<label id="adWhetherDeadlineLabel" for="adWhetherDeadline" class="col-sm-2 control-label">是否限期</label>
					<div class="col-sm-10">
						<select class="form-control" id="adWhetherDeadline"  name="whetherDeadline"  style="width: 100%;">
						</select>
					</div>
				</div>
				<div class="form-group">
					<label id="adStartTimeLabel" for="adStartTime" class="col-sm-2 control-label">开始时间</label>
					<div class="col-sm-4">
						<input id="adStartTime"  class="form-control pull-right" name="startTime"  value="${(cmsAd.startTime?string('yyyy/MM/dd HH:mm:ss'))!}"  type="text" placeholder="选择开始时间...">
					</div>
					<label id="adEndTimeLabel" for="adEndTime" class="col-sm-2 control-label">结束时间</label>
					<div class="col-sm-4">
						<input id="adEndTime"  class="form-control pull-right" name="endTime" type="text" value="${(cmsAd.endTime?string('yyyy/MM/dd HH:mm:ss'))!}" placeholder="选择结束时间...">
					</div>
				</div>
				<div class="form-group">
					<label id="adContentLabel" class="col-sm-2 control-label" >内容</label>
					<div class="col-sm-10">
						<textarea  name="content" id="adContent" data-toggle="jeditor" data-upload="/system/config/file/add?type=1" placeholder="输入内容...">
							${cmsAd.content}
						</textarea>
					</div>
				</div>
				<div class="form-group">
					<label id="adTypeLabel" for="adType" class="col-sm-2 control-label">类别</label>
					<div class="col-sm-2">
						<select class="form-control" id="adType"  name="type" style="width: 100%;">
						</select>
					</div>
					<label id="adWeightLabel" for="adWeight" class="col-sm-2  control-label">广告权重</label>
					<div class="col-sm-2">
						<input  class="form-control" name="weight" id="adWeight" type="number" value="${cmsAd.weight}"  placeholder="请输入...">
					</div>
					<label id="adStatusLabel" for="adStatus" class="col-sm-2  control-label">状态</label>
					<div class="col-sm-2">
						<select class="form-control" id="adStatus"  name="status" style="width: 100%;">
						</select>
					</div>
				</div>
				<div class="form-group">
					<label id="adRemarkLabel" class="col-sm-2 control-label">备注</label>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="remark" id="adRemark" placeholder="输入备注..." value="${cmsAd.remark}"/>
					</div>
				</div>
				<div class="error-message text-center" >
					<span class="error-icon"></span>
					<span id="error-msg" class="error-msg" ></span>
				</div>
             </div>
			<div class="box-footer">
				<div class="pull-right">
               		<button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-paste"></i> 更新</button>
               		<button type="button" class="btn btn-default btn-sm" data-dismiss="modal"><i class="fa fa-close"></i> 关闭</button>
				</div>
          	</div>
		</form>
	</div>
</div>
<script type="text/javascript" src="${request.contextPath}/static/oms/iframe/plugins/jeditor/js/jeditor.js"></script>
<script src="${request.contextPath}/static/oms/iframe/plugins/fileupload/js/vendor/jquery.ui.widget.js"></script>
<script src="${request.contextPath}/static/oms/iframe/plugins/fileupload/js/jquery.fileupload.js"></script>
<script type="text/javascript" src="${request.contextPath}/static/oms/iframe/plugins/bootstrap-image-picker/js/imagePicker.js"></script>
<script type="text/javascript">
function ajaxSubmit(form) {
	
	var $form = $(form);
	
	if ($form.length === 1 && $form.validate()) {
        $.ajax({
            type: 'post',
            url: form.action,
            dataType: "json",
            data: $form.serialize()
        }).done(function(result){
            if (result.success) {
                $("#lgModal").modal('hide');
                alertMsg(result.message,"success");
				dataGridReload();
            } else {
                $form.find(".error-msg").show();
                $form.find(".error-msg").html(result.message);
            }
        });
	}
}

$(function() {
    $("#adStatus").select2({
        data: StatusStore,
        theme: "bootstrap",
        minimumResultsForSearch: Infinity
    }).val('${cmsAd.status}').trigger("change");
    $("#adType").select2({
        data: AdTypeStore,
        theme: "bootstrap",
        minimumResultsForSearch: Infinity
    }).val('${cmsAd.type}').trigger("change");

    var $adWhetherDeadline = $("#adWhetherDeadline");
    $adWhetherDeadline.select2({
        data: WhetherStore,
        theme: "bootstrap",
        minimumResultsForSearch: Infinity
    }).val('${cmsAd.whetherDeadline}').trigger("change");


	$("#adThumbnail").imageDynamicPicker();
	$("#adBanner").imageDynamicPicker();

	$("#adThumbnailFileupload").fileupload({
		url: "/system/config/file/add",
		autoUpload: true,
		dataType: 'json',
		acceptFileTypes: /\.(jpg|png|gif)$/i, //浏览器支持File API才有效
		maxFileSize: 2097152, //2M，浏览器支持File API才有效
		send: function(e, data){
			alertMsg('上传中...',"success");
		},
		done: function (e, data) {
			alertMsg("上传成功", "success");
			$("#adThumbnail").val(data._response.result.data.url);
		},
		fail: function(e, data) {
			alertMsg("上传失败", "success");
		}
	});
	$("#adBannerFileupload").fileupload({
		url: "/system/config/file/add",
		autoUpload: true,
		dataType: 'json',
		acceptFileTypes: /\.(jpg|png|gif)$/i, //浏览器支持File API才有效
		maxFileSize: 2097152, //2M，浏览器支持File API才有效
		send: function(e, data){
			alertMsg('上传中...',"success");
		},
		done: function (e, data) {
			alertMsg("上传成功", "success");
			$("#adBanner").val(data._response.result.data.url);
		},
		fail: function(e, data) {
			alertMsg("上传失败", "success");
		}
	});

    $('[data-toggle="jeditor"]').each(function() {

        var $this = $(this)
        var editor = new jeditor($this);
        var uploadUrl = $this.data('upload');
        editor.config.uploadImgUrl= uploadUrl;
        editor.config.hideLinkImg = true;
        editor.config.uploadImgFileName='file';
        editor.config.containerHeight=200;
        editor.config.uploadImgFns = {
            onload:function (resultText, xhr) {
                var resultObj = eval('(' + resultText + ')');
                console.info('上传结束，返回结果为 ' + resultText);
                var editor = this;
                var originalName = editor.uploadImgOriginalName || '';  // 上传图片时，已经将图片的名字存在 editor.uploadImgOriginalName
                var img;
                if (!resultObj.success) {
                    // 提示错误
                    console.warn('上传失败：' + resultObj.message);
                    alert(resultObj.message);
                } else {
                    console.log('上传成功，即将插入编辑区域，结果为：' + resultText);

                    // 将结果插入编辑器
                    img = document.createElement('img');
                    img.onload = function () {
                        var html = '<img src="' + resultObj.data.urlFull + '" alt="' + originalName + '" style="max-width:100%;"/>';
                        editor.command(null, 'insertHtml', html);

                        console.log('已插入图片，地址 ' + resultObj.data.urlFull);
                        img = null;
                    };
                    img.onerror = function () {
                        console.error('使用返回的结果获取图片，发生错误。请确认以下结果是否正确：' + resultObj.data.urlFull);
                        img = null;
                    };
                    img.src = resultObj.data;
                }

            }
        };
        editor.create();
    });

    //初始化时间选择器
    $('[name=startTime]').datetimepicker({
        format:"Y/m/d 00:00:00",      //格式化日期
        timepicker:true,    //开启时间选项
        yearStart:2000,     //设置最小年份
        yearEnd:2050,        //设置最大年份
        todayButton:false    //关闭选择今天按钮
    });

    //初始化时间选择器
    $('[name=endTime]').datetimepicker({
        format:"Y/m/d 23:59:59",      //格式化日期
        timepicker:true,    //开启时间选项
        yearStart:2000,     //设置最小年份
        yearEnd:2050,        //设置最大年份
        todayButton:false    //关闭选择今天按钮
    });

	$.ajax({
		type:"get",
		url:'/cms/ad/category/list',
		dataType:'json'
	}).done(function(result){
		var o = [];
		var a = result;
		$.each(a, function() {
			if(this.id !== undefined && this.id !==''){
				o.push({'id':this.id,'text':this.name});
			}
		});
		$("#adCategoryId").select2({
			data:o,
			placeholder: "广告类目...",
			allowClear: true,
			language: "zh-CN",
			theme: "bootstrap"
		}).val('${cmsAd.adCategoryId}').trigger("change");
	});


	var $editForm = $("#editForm");
	$editForm.validate({
        rules: {
            name: {
                required: true
            },
            weight: {
                required: true
            },
            status: {
                required: true
            }
        },
        messages: {
            name:{
                required:"名称不能为空！"
            },
            weight:{
                required:"广告权重不能为空！"
            },
            status:{
                required:"状态不能为空！"
            }
        },
		submitHandler:ajaxSubmit,
		errorLabelContainer:".error-msg",
		wrapper:"li",
		showErrors:function(errorMap,errorList) {
			if(errorList.length>0){
				$editForm.find(".error-msg").html(errorList[0].message);
			}else{
				$editForm.find(".error-msg").html("");
			}
		},
		onkeyup: false
	});
});
</script>